package com.easondongh.system.vo;

import com.easondongh.system.constants.Constants;
import com.easondongh.system.domain.SysMenu;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;

/**
 * 菜单树节点
 * 菜单又分为顶部菜单、侧边菜单
 *
 * @author EasonDongH
 * @date 2020/4/29 13:59
 */
@Data
public class MenuTreeNode {

    private Integer id;
    private Integer pid;
    @JsonInclude(JsonInclude.Include.NON_NULL)
    private String title;
    private String href;
    private String icon;
    private Boolean spread;
    @JsonInclude(JsonInclude.Include.NON_NULL)
    private String target;
    @JsonInclude(JsonInclude.Include.NON_NULL)
    private String typeCode;
    @JsonInclude(JsonInclude.Include.NON_EMPTY)
    private List<MenuTreeNode> child = new ArrayList<>();

    /**
     * 用于构造侧边树
     * @param id
     * @param pid
     * @param title
     * @param href
     * @param icon
     * @param spread
     * @param target
     * @param typeCode
     */
    public MenuTreeNode(Integer id, Integer pid, String title, String href, String icon, Boolean spread, String target, String typeCode) {
        this.id = id;
        this.pid = pid;
        this.title = title;
        this.href = href;
        this.icon = icon;
        this.spread = spread;
        this.target = target;
        this.typeCode = typeCode;
    }

    public static class MenuTreeNodeBuilder {

        /**
         * 递归构造菜单树
         * @param curLevel
         * @param nodes
         * @return
         */
        public static List<MenuTreeNode> build(Integer curLevel, List<SysMenu> nodes) {
            List<MenuTreeNode> result = new ArrayList<>();
            build(curLevel,nodes,result);
            return result;
        }

        private static void build(Integer curLevel, List<SysMenu> nodes, List<MenuTreeNode> treeNodes) {
            for (SysMenu node : nodes) {
                if(node.getPid().equals(curLevel)) {
                    List<MenuTreeNode> childs = build(node.getId(), nodes);
                    MenuTreeNode treeNode = new MenuTreeNode(node.getId(), node.getPid(), node.getTitle(), node.getHref(), node.getIcon(),
                            Constants.MENU_SPREAD.equals(node.getSpread()),node.getTarget(),node.getTypeCode());
                    treeNode.setChild(childs);
                    treeNodes.add(treeNode);
                }
            }
        }
    }
}
